import styles from './index.less';
import { useState, useEffect } from 'react';
import { history, useIntl, Link } from 'umi';
import { Button, Table, Radio, Divider, Space, message, Tabs } from 'antd';
import request from '@/utils/request';
import NoDataExplain from './components/explain';

const { TabPane } = Tabs;

const CampaignsPage = function () {
  const intl = useIntl();

  const stateMap = {
    C: intl.formatMessage({ id: 'sent' }),
    O: intl.formatMessage({ id: 'scheduled' }),
    D: intl.formatMessage({ id: 'draft' }),
  };

  const columns1 = [
    {
      title: intl.formatMessage({ id: 'status' }),
      dataIndex: 'state',
      render: (text: string) => (
        <div className={styles.statecon}>
          <div className={`${styles.state} ${styles[text]}`}></div>
          {stateMap[text]}
        </div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'title' }),
      dataIndex: 'title',
      render: (text: string, record: any) => (
        <Link to={`/campaigns/create?id=${record.id}&type=${tab}`}>
          {record.template?.title}
        </Link>
      ),
    },
    {
      title: intl.formatMessage({ id: 'user' }),
      dataIndex: 'source',
    },
    {
      title: intl.formatMessage({ id: 'sentTime' }),
      dataIndex: 'sendTime',
      render: (text: string) => <div>{text || '-'}</div>,
    },
  ];
  const columns2 = [
    {
      title: intl.formatMessage({ id: 'title' }),
      dataIndex: 'title',
      render: (text: string, record: any) => (
        <Link to={`/campaigns/create?id=${record.id}&type=${tab}`}>{text}</Link>
      ),
    },
    {
      title: intl.formatMessage({ id: 'sentCount' }), // 用了多少次
      dataIndex: 'useNumber',
    },
    {
      title: intl.formatMessage({ id: 'lastedited' }),
      dataIndex: 'updatedDate',
    },
    {
      title: intl.formatMessage({ id: 'sentTime' }),
      dataIndex: 'sendTime',
      render: (text: string) => <div>{text || '-'}</div>,
    },
  ];
  const [tab, setTab] = useState('1');

  const [campaignList, setCampaignList] = useState([]);
  const [templateList, setTemplateList] = useState([]);

  const [tableSelect, setTableSelect] = useState([]);

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setTableSelect(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  useEffect(() => {
    getList1();
    getList2();
  }, []);

  const getList1 = () => {
    request.get('/campaign/get').then((res) => {
      setCampaignList(res.data.campaignList);
    });
  };
  const getList2 = () => {
    request.get('/template/get').then((res) => {
      setTemplateList(res.data.templateList);
    });
  };

  const onRemove = () => {
    request.post('/template/del', tableSelect).then((res) => {
      message.success(intl.formatMessage({ id: 'removesuccess' }));
      getList2();
    });
  };

  const onCreate = () => {
    history.push(`/campaigns/create?type=${tab}`);
  };

  const onChangeTab = (tab: string) => {
    setTab(tab);
  };

  return (
    <div className={styles.CampaignsContainer}>
      <Tabs
        type="card"
        defaultValue={tab}
        className="cardtab"
        onChange={onChangeTab}
      >
        <TabPane
          tab={intl.formatMessage({ id: 'campaign' })}
          key="1"
          className={styles.tabpane}
        >
          <Table
            className="nodatanoshow"
            style={{ margin: '20px 20px 0' }}
            rowKey="id"
            columns={columns1}
            dataSource={campaignList}
            pagination={{
              showTotal: (total) =>
                `${intl.formatMessage({ id: 'total' })}: ${total}`,
            }}
          />
          {campaignList.length < 1 ? <NoDataExplain /> : null}
        </TabPane>
        <TabPane
          tab={intl.formatMessage({ id: 'template' })}
          key="2"
          className={styles.tabpane}
        >
          <div className={styles.ccHead}>
            <Space>
              {tableSelect.length ? (
                <Button onClick={onRemove}>
                  {intl.formatMessage({ id: 'remove' })}
                </Button>
              ) : null}
              <Button type="primary" onClick={onCreate}>
                {intl.formatMessage({ id: 'createcampaigns' })}
              </Button>
            </Space>
          </div>
          <Table
            className="nodatanoshow"
            style={{ margin: '0 20px' }}
            rowKey="id"
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            columns={columns2}
            dataSource={templateList}
            pagination={{
              showTotal: (total) =>
                `${intl.formatMessage({ id: 'total' })}: ${total}`,
            }}
          />
          {templateList.length < 1 ? <NoDataExplain /> : null}
        </TabPane>
      </Tabs>
    </div>
  );
};

CampaignsPage.title = '营销群发讯息';

export default CampaignsPage;
